<?php

/**
 * Registers a module that routes the request to a public resource of the
 * specified module.
 *
 * @author    Mon Zafra <monzee at gmail>
 * @copyright (c)2009 Mon Zafra
 * @category  Mz
 * @pacakge   Mz_Module
 * @license   http://mz-project.googlecode.com/svn/trunk/LICENSE     MIT License
 * @version   SVN: $Id: Resource.php 3 2009-02-18 18:55:27Z monzee $
 */
class Mz_Module_Resource extends Zend_Controller_Plugin_Abstract
{
    protected $_resourcesModule = 'resource';

    /**
     * Returns the resource mapper module name.
     * @return string
     */
    public function getResourcesModule()
    {
        return $this->_resourcesModule;
    }

    /**
     * Sets the resource mapper module name.
     * 
     * @param string $module
     */
    public function setResourcesModule($module)
    {
        $this->_resourcesModule = $module;
    }

    /**
     * If the request maps to the resource mapper module, force dispatch to
     * IndexController if the controller does not exist.
     *
     * @param Zend_Controller_Request_Abstract $request
     */
    public function routeShutdown(Zend_Controller_Request_Abstract $request)
    {
        $resModule = $this->_resourcesModule;
        $front = Zend_Controller_Front::getInstance();
        if ($request->getModuleName() == $resModule) {
            $dispatcher = $front->getDispatcher();
            $dispatcher->setParam('useDefaultControllerAlways', true);

            // manually assign the controller since the module name
            // might not match the class name
            if ('resource' !== $this->_resourcesModule) {
                $path = $dispatcher->getControllerDirectory($resModule);

                $dispatcher->removeControllerDirectory('resource');
                $dispatcher->addControllerDirectory($path, 'resource');
            }

            $request->setModuleName('resource')
                    ->setParam('resourceModule', $this->_resourcesModule);
        }
    }

}
